<template>
  <el-card class="box-card">
    <div class="mgmt-user">
      <div class="operate">
        <el-button type="primary" @click="openModel(1)">新建</el-button>
        <el-button type="primary" @click="openTag(1)">标签</el-button>
      </div>
      <div class="table">
        <UnTable 
          :tableData="tableData"
          :tableOption="tableOption"
          @pageChange="pageChange"
        >
          <template #action="{scope}">
                <el-button size="small" type="primary" @click="eidtBook(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteBook(scope.row)">删除</el-button>
          </template>
        </UnTable>
      </div>
    </div>
  </el-card>
  <el-dialog v-model="dialogVisible" title="添加账单" width="30%" :close-on-click-modal="false">
    <div class="userForm">
      <el-form :model="form" label-width="120px" label-position="top" ref="ruleFormRef" :rules="rules">
        <el-form-item prop="time" label="请选择时间">
          <el-date-picker
            v-model="form.time"
            type="date"
            placeholder="请选择时间"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item prop="tag" label="请选择类别">
          <el-cascader v-model="form.tag" :options="option" placeholder="请选择标签" style="width: 100%" />
        </el-form-item>
        <el-form-item prop="price" label="请输入价格">
          <el-input v-model="form.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item prop="depict" label="请输入描述">
          <el-input v-model="form.depict" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit()">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <Tag v-if="dialogVisibleTag" :visible="dialogVisibleTag" @closed="closeCurrentModal"></Tag>
</template>

<script setup>
import { onMounted, ref, reactive } from 'vue'
import { getTags, addBook, getBook, deleteBookApi, editBook } from '@/api/book' //api/后面不能大写Mgmt
import { ElMessage, ElMessageBox } from 'element-plus'
import { listToTree } from '@/utils/index.js'
import Tag from './tag.vue'
import {TableOption}  from '@/class/table.js'
import UnTable from '@/components/UnTable/index.vue'
const dialogVisibleTag = ref(false)
function useTableHooks(){
  const table =ref({
    tableColumn: [
      { label: '时间', prop: 'time',sortable:true },
      { label: '类别', prop: 'leave1'},
      { label: '小类', prop: 'leave2'},
      { label: '金额', prop: 'price'},
      { label: '描述', prop: 'depict' },
    ]
  })
  const tableOption = ref(new TableOption(table.value))
  const pageChange = async (val) => { 
    if(val.type==='currentPage'){
      tableOption.value.pageNum=val.pageNum
    }else{
      tableOption.value.pageSize=val.pageSize
      tableOption.value.pageNum=val.pageNum
    }
    getList()
  }
  return {tableOption,pageChange}
}
const {tableOption,pageChange} = useTableHooks()
const openTag = ()=>{
  dialogVisibleTag.value=true
}
const closeCurrentModal=()=>{
  dialogVisibleTag.value=false
}
const tableData = ref([])
const option = ref([])
const dialogVisible = ref(false)
const form = reactive({
  time: '',
  tag: '',
  price: '',
  depict: ''
})
const rules = reactive({
  time: [{ required: true, message: '请选择时间', trigger: 'blur' }],
  tag: [{ required: true, message: '请选择标签', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
})
const listOption = ref([])
const initData = async () => {
  const res = await getTags()
  if (res.code === 200) {
    listOption.value = res.data
    let list = res.data.map((item) => {
      return {
        pid: item.pid.toString(),
        id: item.id.toString(),
        name: item.name,
        label: item.name,
        value: item.id
      }
    })
    let tree = listToTree(list)
    option.value = tree
  }
}
const getList = async () => {
  const res = await getBook({pageNum: tableOption.value.pageNum, pageSize: tableOption.value.pageSize})
  if (res.code === 200) {
    tableData.value = res.data.list
    tableOption.value.total= res.data.total
  }
}
const openModel = (type, value) => {
  dialogVisible.value = true
  form.time = ''
  form.price = ''
  form.depict = ''
  form.tag = []
  form.id = null
}
const ruleFormRef = ref(null)
const submit = () => {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      let param = { ...form }
      param.leave1 = listOption.value.find((item) => item.id === form.tag[0]).name
      param.leave2 = listOption.value.find((item) => item.id === form.tag[1]).name
      const fn = form.id ? editBook : addBook
      const res = await fn(param)
      if (res.code === 200) {
        ElMessage({ type: 'success', message: '添加成功' })
        ruleFormRef.value.resetFields()
        dialogVisible.value = false
        getList()
      }
    }
  })
}
const eidtBook = (val) => {
  dialogVisible.value = true
  form.time = val.time
  form.price = val.price
  form.depict = val.depict
  let tag1 = listOption.value.find((item) => item.name === val.leave1).id
  let tag2 = listOption.value.find((item) => item.name === val.leave2).id
  form.tag = [tag1, tag2]
  form.id = val.id
}
const deleteBook = (row) => {
  ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await deleteBookApi({ id: row.id })
      if (res.code === 200) {
        ElMessage({ type: 'success', message: '删除成功' })
        getList()
      }
    })
    .catch(() => {
      ElMessage({ type: 'info', message: '已取消删除' })
    })
}
onMounted(() => {
  initData()
  getList()
})
</script>
<style lang="scss" scoped>
.mgmt-user {
  .operate {
    margin: 20px 0;
    display: flex;
    .input {
      width: 250px;
      margin-right: 20px;
    }
  }
}

.userForm {
  .el-select {
    width: 100%;
  }
}
.table{
  height: 600px;
}
</style>
